package com.zhdl.network.other_protocol.modbustcp.after;

import cn.hutool.core.util.HexUtil;
import com.project.command.instruction.strategy.abs.AbsAfterControlCommand;
import com.project.command.instruction.strategy.process.data.AfterStrategyParam;
import com.project.common.util.ByteHelper;
import com.zhdl.common.ytools.eventbus.center.EventBusCenter;
import com.zhdl.network.other_protocol.modbustcp.dto.ModbusTcpDto;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service(ModbusTcpAfterService.MODBUS_TCP_AFTER_SERVICE)
public class ModbusTcpAfterService extends AbsAfterControlCommand<ModbusTcpDto, ByteBuf> {
    public static final String MODBUS_TCP_AFTER_SERVICE = "modbusTcpAfterService";

    /**
     * 后置处理结果判断
     *
     * @param resp
     * @return /
     */
    @Override
    public boolean afterResultJudge(AfterStrategyParam resp) {
        log.debug("MODBUS_TCP_AFTER_SERVICE modbusTcpAfterService");

        List<byte[]> bytes = resp.getNewData();
        byte[] bytes1 = bytes.get(0);
        String s = HexUtil.encodeHexStr(bytes1);
        System.out.println("当前接收数据为:------->" + s);
        ModbusTcpDto ModbusTcpDto = new ModbusTcpDto();
        String substring = s.substring(14);
        String instruction = resp.getInstruction().replaceAll(" ", "");
        String type = instruction.substring(14, 16);
        ModbusTcpDto.setCmdType((byte) Integer.parseInt(type));

        switch (type) {
            case "06", "05", "10", "0F" -> {
                ModbusTcpDto.setFullBuff(bytes1);
                ModbusTcpDto.setUnitBuff(ByteHelper.hexString2Bytes(substring));
            }
            case "01", "03", "02" -> {
                ModbusTcpDto.setFullBuff(bytes1);
                ModbusTcpDto.setUnitBuff(ByteHelper.hexString2Bytes(substring.substring(4)));
            }
            default -> {
                System.out.println("功能码为：" + type + "，未匹配到对应的功能码");
            }
        }
        List<ModbusTcpDto> temp = new ArrayList<>();
        temp.add(ModbusTcpDto);
        resp.setNewData(temp);
        EventBusCenter.getEventBus().post(resp);
        log.info("tcp:----" + resp.getPortKey() + "发送指令>>>>" + resp.getInstruction() + "收到指令》》》》" + HexUtil.encodeHexStr(ModbusTcpDto.getFullBuff()));
        return true;
    }

    /**
     * 判断 读取 3200 状态字数据
     */
    public String getMotorStatus(ModbusTcpDto ModbusTcpDto) {
        byte[] unitBuff = ModbusTcpDto.getUnitBuff();
        return HexUtil.encodeHexStr(unitBuff);
    }

}
